package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.config.redis.service.RedisService;
import org.example.constants.UserConstant;
import org.example.domain.User;
import org.example.mapper.UserMapper;
import org.example.service.UserService;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * (User)表服务实现类
 *
 * @author hsx
 * @since 2023-10-10 15:15:17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public User selectUserById(Long id) {
        // 1. 查询缓存中是否存在
        if (redisService.hasKey(UserConstant.USER_Id + id)) {
            return redisService.getCacheObject(UserConstant.USER_Id + id);
        }

        // 2. 查询数据库
        User user = getById(id);
        if (user == null) {
            return null;
        }
        redisService.setCacheObject(UserConstant.USER_Id + id, user, 5L, TimeUnit.MINUTES);
        return user;
    }

    @Override
    public User
    selectUserByUsername(String username) {
        // 布隆过滤器
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter(UserConstant.BLOOM_USER_USERNAME);
        if (!bloomFilter.contains(username)) {
            return null;
        }

        // 1. 查询缓存中是否存在
        if (redisService.hasKey(UserConstant.USER_USERNAME + username)) {
            return redisService.getCacheObject(UserConstant.USER_USERNAME + username);
        }

        // 2. 查询数据库
        User user = getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if (user == null) {
            return null;
        }
        redisService.setCacheObject(UserConstant.USER_USERNAME + username,
                user, 5L, TimeUnit.MINUTES);
        return user;
    }
}

